package com.netty.clientserver.serve;

import com.netty.clientserver.handler.MyWebSocketChannelHandler;
import com.netty.common.constant.Constants;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.mbeans.JmxRemoteLifecycleListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import io.netty.channel.ChannelHandler;
/**
 * @author LiuXiaoYu
 * @date 2022/2/2- 13:44
 */
@ChannelHandler.Sharable
@Component
@Slf4j
public class NettyServer {

    NioEventLoopGroup bossGroup=new NioEventLoopGroup(1);
    NioEventLoopGroup workGroup=new NioEventLoopGroup();

    @Autowired
    private MyWebSocketChannelHandler myWebSocketChannelHandler;

    public void run(Integer port){

        try{
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup,workGroup)
                    //服务端可连接队列数,对应TCP/IP协议listen函数中backlog参数
                    .option(ChannelOption.SO_BACKLOG, Constants.TCP_LISTEN)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(myWebSocketChannelHandler);
            System.out.println("客户端等待连接....");
            Channel ch = bootstrap.bind(port).sync().channel();
            ch.closeFuture().sync();
        }catch (Exception e){
            log.info("服务端启动异常:{},异常信息:{}",e,e.getMessage());
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

}
